from fastapi import Depends, APIRouter, routing, Request
from sqlalchemy.orm import Session

from app.common.http.http_result import Success, Error
from models.pagination import Pagination
from models.user_model import User, UserCreate
from services.db import get_db_session
from services.user_service import UserService, get_user_service

router = APIRouter(prefix="/user", tags=["user"])


@router.get("/detail/{user_id}")
async def get_user(user_id: str, service: UserService = Depends(get_user_service),
                   db: Session = Depends(get_db_session)):
    return Success(service.get_user_by_id(user_id, db))


@router.get("/list")
async def list_users(request: Request, pagination: Pagination = Depends(Pagination),
                     db_session: Session = Depends(get_db_session), service: UserService = Depends(get_user_service)):
    # 等待redis写入  await异步变同步 如果不关心结果可以不用await，但是这里下一步要取值，必须得先等存完值 后再取值
    # await request.app.state.redis.set("aa", page)
    # 等待 redis读取
    # v = await request.app.state.redis.get("aa")
    try:
        users, count = service.list_users(pagination.page, pagination.page_size, db_session)
        return Success(users, total=count, pagination=pagination)
    except Exception as e:
        return Error(str(e))


@router.post("/add")
async def create_user(user: UserCreate, service: UserService = Depends(get_user_service),
                      db: Session = Depends(get_db_session)):
    return Success(service.add_user(user, db))
